<template>
    <div>
      <VForm
        ref="vformComponents"
        :form="formData.form"
        :options="formData.options"
        :rules="formData.rules"
        :labelWidth="formData.labelWidth"
        :rowspan="rowspan"
        @changeAddress="changeAddress"
        @changeGdArea="changeGdArea"
        @toLoadMethods="toLoadMethods"
      ></VForm>
      <div class="e-dialog-footer">
      <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button v-if="openType != 'detail'" type="primary" @click="sure">确 定</el-button>
    </span>
      </div>
    </div>
</template>

<script>
  import { riskHazardDetail,
    riskHazardUpdate,
    riskHazardAdd } from '@/api/risk/riskHazard'
  import { treeDataChild} from '@/api/risk/treeData'
  import { alarmFacilityList} from '@/api/alarm/facility'
  import VForm from "@/components/VForm/index";
  export default {
    components: {
      VForm,
    },
    props: {
      width: {
        type: String,
        default: "70%",
      },
      title: {
        type: String,
        default: "详情",
      },
      id:{},
      openType:{
        type:String,
        default:"add"
      },
      dialogVisible: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      'width': {
        handler(newVal, oldVal) {
          console.log('newVal===',newVal, oldVal)
          let w = this.width.split('%')[0]
          if(w>=60){
            this.rowspan = 2
          }else{
            this.rowspan = 1
          }
        },
        deep: true,
        immediate: true
      },
      'bClassifyOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='bclassify'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'sClassifyOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='sclassify'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'categoryOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='category'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'gradeOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='grade'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'stateOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='state'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'facilityOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='facilityId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      dialogVisible:{
        handler(newVal, oldVal) {
          if(newVal){
            console.log("监测指===",newVal)
            this.getData()
          }
        },
        deep: true,
        immediate: true
      },
      openType:{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            t.disabled = newVal == 'detail' ? true : false
          })
        },
        deep: true,
        immediate: true
      }
    },
    computed: {
      isVisible: {
        get() {
          return this.dialogVisible
        },
        set() {
          this.close()
        }
      }
    },
    data() {
      return {
        rowspan:1,
        dict:{},
        formData: {
          form: {
            flagCode:"1",
            reportTime:"",
            name:"",
            bclassify:"",

            sclassify:"",
            category:"",
            address:"",
            memo:"",
            grade:"",
            state:"",
            reportName:"",
            reportContact:"",
            handleUnit:"",
            handleName:"",
            acceptTime:"",
            handleMemo:"",
            handleTime:"",
            handleReport:[],
            sceneFile:[],
            objClassify:"",
            objName:"",
            lon:"",
            lat:"",
            provinceCode:"",
            cityCode:"",
            countyCode:"",
            areaCode:"",
            updateTime:"",
            updateBy:"",
            requireCompleteTime:"",
            reportUnit:"",
            img:[],
            discoveryTime:"",
            handleProcess:"",
            handleImg:[],
            mapData:null,

            facilityId:'',
            facilityName:'',
          },
          options: [

            {
              title: "上报时间",
              key: "reportTime",
              type: "date",
            },
            {
              title: "隐患名称",
              key: "name",
              type: "text",
            },
            {
              title: "隐患大类",
              key: "bclassify",
              type: "select",
              multiple:false,
              event:'changeBclassify',
              option: {
                data: this.bClassifyOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },
            {
              title: "隐患细类",
              key: "sclassify",
              type: "select",
              multiple:false,
              event:'changeSclassify',
              option: {
                data: this.sClassifyOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },




            {
              title: "三级类别",
              key: "category",
              type: "select",
              multiple:false,
              option: {
                data: this.categoryOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },

            {
              title: "设施名称",
              key: "facilityId",
              type: "select",
              multiple:false,
              event:'changeFacilityName',
              option: {
                data: this.facilityOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },

            {
              title: "隐患等级",
              key: "grade",
              type: "select",
              multiple:false,
              option: {
                data: this.gradeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "上报单位",
              key: "reportUnit",
              type: "text",
            },
            {
              title: "上报人",
              key: "reportName",
              type: "text",
            },
            {
              title: "上报人电话",
              key: "reportContact",
              type: "text",
            },
            {
              title: "发现时间",
              key: "discoveryTime",
              type: "date",
            },
            {
              title: "隐患地址",
              type:'mapPosition',
              key:'mapData',
            },
            {
              title: "现场照片",
              key: "img",
              type: "file",
              fileType: "image",
              listType: "picture-card",
              uploadTextTip: "",
              columnWidth: 'w100max'
            },
            {
              title: "隐患描述",
              key: "memo",
              type: "textarea",
              columnWidth: 'w100max'
            },
            {
              title: "隐患状态",
              key: "state",
              type: "select",
              multiple:false,
              option: {
                data: this.stateOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "隐患处置单位",
              key: "handleUnit",
              type: "text",
            },
            {
              title: "处置负责人",
              key: "handleName",
              type: "text",
            },
            {
              title: "处置过程",
              key: "handleProcess",
              type: "text",
            },
            {
              title: "隐患受理时间",
              key: "acceptTime",
              type: "date",
            },
            {
              title: "要求整改完成时间",
              key: "requireCompleteTime",
              type: "date",
            },
            {
              title: "处置完成时间",
              key: "handleTime",
              type: "date",
            },
            {
              title: "处置照片",
              key: "handleImg",
              type: "file",
              fileType: "image",
              listType: "picture-card",
              uploadTextTip: "",
              columnWidth: 'w100max'
            },
            {
              title: "隐患处置简述",
              key: "handleMemo",
              type: "textarea",
              columnWidth: 'w100max'
            },
            {
              title: "隐患现场文件",
              key: "sceneFile",
              type: "file",
              fileType:"file",
              listType:"text",
              uploadTextTip:""
            },
            {
              title: "隐患处置报告",
              key: "handleReport",
              type: "file",
              fileType:"file",
              listType:"text",
              uploadTextTip:""
            },
          ],
          rules: {
            flagCode :[
              {max:20, message: '长度最大为20个字符', trigger: 'blur'}
            ],
            reportTime :[
              { required: true, message: '请输入', trigger: 'blur' }
            ],
            name :[
              { required: true, message: '请输入', trigger: 'blur' },
              {max:64, message: '长度最大为64个字符', trigger: 'blur'}
            ],
            bclassify :[
              { required: true, message: '请选择', trigger: 'blur' }
            ],
            sclassify :[
              { required: true, message: '请选择', trigger: 'blur' }
            ],
            category :[
              { required: true, message: '请选择', trigger: 'blur' }
            ],
            address :[
              {max:200, message: '长度最大为200个字符', trigger: 'blur'}
            ],
            memo :[
              {max:1024, message: '长度最大为1024个字符', trigger: 'blur'}
            ],
            grade :[
              { required: true, message: '请选择', trigger: 'blur' }
            ],
            state :[
              { required: true, message: '请选择', trigger: 'blur' }
            ],
            reportName :[
              {max:50, message: '长度最大为50个字符', trigger: 'blur'}
            ],
            reportContact :[
              {max:20, message: '长度最大为20个字符', trigger: 'blur'}
            ],
            handleUnit :[
              {max:128, message: '长度最大为128个字符', trigger: 'blur'}
            ],
            handleName :[
              {max:50, message: '长度最大为50个字符', trigger: 'blur'}
            ],
            acceptTime :[
            ],
            handleMemo :[
              {max:1024, message: '长度最大为1024个字符', trigger: 'blur'}
            ],
            handleTime :[
            ],
            handleReport :[

            ],
            sceneFile :[
            ],
            lon :[
              {max:36, message: '长度最大为36个字符', trigger: 'blur'}
            ],
            lat :[
              {max:36, message: '长度最大为36个字符', trigger: 'blur'}
            ],
            provinceCode :[
              {max:12, message: '长度最大为12个字符', trigger: 'blur'}
            ],
            cityCode :[
              {max:12, message: '长度最大为12个字符', trigger: 'blur'}
            ],
            countyCode :[
              {max:12, message: '长度最大为12个字符', trigger: 'blur'}
            ],
            areaCode :[
              {max:12, message: '长度最大为12个字符', trigger: 'blur'}
            ],

          },
          labelWidth: "140px",
        },
        // 字典
        bClassifyOptions:[],
        sClassifyOptions:[],
        categoryOptions:[],
        gradeOptions:[],
        stateOptions:[],
        facilityOptions:[]
      };
    },
    methods: {
      toLoadMethods(methods){
        this[methods]();
      },

      changeFacilityName(){
        var label = this.facilityOptions.find(t=>t.name==this.formData.form.facilityId).label;
        this.formData.form.facilityName=label;

      },

      changeBclassify(){
        this.formData.form.sclassify='';
        this.sClassifyOptions=[];

        this.formData.form.category='';
        this.categoryOptions=[];

        this.formData.form.facilityId='';
        this.formData.form.facilityName='';
        this.facilityOptions=[];

        this.sendBclassifyData();
      },

      async sendBclassifyData(){
        let queryData ={}
        queryData.name='hazardBClassify';
        queryData.code =this.formData.form.bclassify;
        let res =await treeDataChild(queryData);
        if(res.code==200) {
          let that = this
          res.data.forEach(function (item,index){
            var one ={}
            one.label= item.label;
            one.name=item.code;
            one.modeType=item.modeType;
            that.sClassifyOptions.push(one);
          })

          if(this.formData.form.sclassify!=''){
            this.sendFacilityData();
          }
        }
      },
      changeSclassify(){
        this.formData.form.category='';
        this.categoryOptions=[];
        this.sendCategoryData();

        this.formData.form.facilityId='';
        this.formData.form.facilityName='';
        this.facilityOptions=[];
        this.sendFacilityData();

      },

      async sendCategoryData(){
        let queryData ={}
        queryData.name='hazardSClassify';
        queryData.code =this.formData.form.sclassify;
        let res =await treeDataChild(queryData);
        if(res.code==200) {
          let that = this
          res.data.forEach(function (item,index){
            var one ={}
            one.label= item.label;
            one.name=item.code;
            that.categoryOptions.push(one);
          })
        }
      },

      async sendFacilityData(){
        let queryData ={}

        let modeType = this.sClassifyOptions.find(t=>t.name==this.formData.form.sclassify).modeType;

        queryData.modeType="ALARM_"+modeType;
        queryData.areaCodeFormat = this.$store.state.account.user.deptIds;
        let res =await alarmFacilityList(queryData);
        if(res.code==200) {
          let that = this
          res.data.forEach(function (item,index){
            var one ={}
            one.label=item.name ;
            one.name=item.id;
            that.facilityOptions.push(one);
          })

        }

      },


      getCountySubIndex(cityCode){
        // 中山、东莞截取10位
        let filterList = ['442000000000','441900000000']
        if(filterList.findIndex(t=>t==cityCode)>-1){
          return 10;
        }
        return 6;
      },
      positionSubmitFormat(){

        let mapData = this.formData.form.mapData
        console.log(">>>");
        console.log(mapData);
        if(mapData){
          this.formData.form.lon = mapData.gpsX
          this.formData.form.lat = mapData.gpsY
          this.formData.form.address = mapData.address
          this.formData.form.areaCode = mapData.towncode
          if(mapData.towncode){
            this.formData.form.provinceCode = mapData.towncode.substr(0,2).padEnd(12,'0')
            this.formData.form.cityCode = mapData.towncode.substr(0,4).padEnd(12,'0')
            let subIndex = this.getCountySubIndex(this.formData.form.cityCode)
            this.formData.form.countyCode = mapData.towncode.substr(0,subIndex).padEnd(12,'0')
          }
        }
      },
      positionLoadFormat(){
        let form = this.formData.form
        let mapData = {}


        mapData.address = form.address
        mapData.gpsX = parseFloat(form.lon)
        mapData.gpsY = parseFloat(form.lat)
        mapData.towncode = form.areaCode
        this.formData.form.mapData = mapData




        console.log("mpap",mapData)
      },


      submitFormat(){
        this.formData.form.sceneFile = JSON.stringify(this.formData.form.sceneFile);
        this.formData.form.handleReport = JSON.stringify(this.formData.form.handleReport);
        this.formData.form.img = JSON.stringify(this.formData.form.img);
        this.formData.form.handleImg = JSON.stringify(this.formData.form.handleImg);

      },
      loadFormat(){
         this.formData.form.sceneFile  =  this.formData.form.sceneFile!=null ? JSON.parse(this.formData.form.sceneFile) : [];
         this.formData.form.handleReport  = this.formData.form.handleReport!=null ? JSON.parse(this.formData.form.handleReport) : [];
        if(this.formData.form.img!=null && this.formData.form.img!='' && this.formData.form.img!='null'){
          this.formData.form.img = JSON.parse( this.formData.form.img ).map(item=>{
            return{
              name:item.name,
              url: process.env.VUE_APP_BASE_API + 'file/api/download/'+item.fileId,
              uid: item.uuid,
              fileId: item.fileId,
            }
          })
        }else {
          this.formData.form.img = []
        }
        if(this.formData.form.handleImg!=null &&
          this.formData.form.handleImg!='' && this.formData.form.handleImg!='null'){
          this.formData.form.handleImg = JSON.parse( this.formData.form.handleImg ).map(item=>{
            return{
              name:item.name,
              url: process.env.VUE_APP_BASE_API + 'file/api/download/'+item.fileId,
              uid: item.uuid,
              fileId: item.fileId,
            }
          })
        }else {
          this.formData.form.handleImg = []
        }
      },
      getCheckBoxData(value,option,type){
        if(type=="submit"){
          if(value.length==0){
            return null
          }
          let temp = [];
          value.forEach(t=>{
            let item = option.find(x=> x.label == t)
            if(item!=undefined){
              temp.push(item.value)
            }
          })
          return temp.join(",")
        }else {
          if(!value){
            return []
          }else {
            let data = value.split(",")
            let temp = []
            data.forEach(t=>{
              let item = option.find(x=> x.value == t)
              if(item!=undefined){
                temp.push(item.label)
              }
            })
            return temp
          }
        }
      },
      sure(){
        console.log('sure===',this.formData.form)
        this.$refs.vformComponents.$refs.form.validate().then(res=>{
          this.submitFormat()
          this.positionSubmitFormat()
          if(this.openType == "add"){
            this.add()
          }else{
            this.update()
          }
        })
      },
      add(){
        this.formData.form.id = null
        this.formData.form.delFlag=0;

        riskHazardAdd(this.formData.form).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.createSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      update(){
        riskHazardUpdate(this.formData.form).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.updateSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      cancel(){
        this.close()
      },
      handleClose(done) {
        done()
        this.close()
      },
      closeSuccess(){
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$emit('success')

        this.facilityOptions=[];
        this.categoryOptions=[];

      },
      close(){

        this.$refs.vformComponents.$refs.form.resetFields();
        this.$refs.vformComponents.$refs.mapPosition[0].reloadMap();
        this.$emit('close')

        this.facilityOptions=[];
        this.categoryOptions=[];
      },
      getData(){

        // 获取字典值
        this.bClassifyOptions = []
        this.$commonJs.filterDataDict("hazardBClassify",this.bClassifyOptions )

        this.sClassifyOptions = []
        //this.$commonJs.filterDataDict("hazardSClassify",this.sClassifyOptions )


        this.categoryOptions = []
        //this.$commonJs.filterDataDict("hazardCategory",this.categoryOptions )

        this.gradeOptions = []
        this.$commonJs.filterDataDict("patrolHazardLevel",this.gradeOptions )

        this.stateOptions = []
        this.$commonJs.filterDataDict("hazardDealState",this.stateOptions )

        if(this.openType!="add"){
          riskHazardDetail(this.id).then(res=>{
            if(res.code==200){
              this.formData.form = res.data

              this.sendBclassifyData()
              this.sendCategoryData();
              this.loadFormat()
              this.positionLoadFormat()
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          })
        }
      },

      changeAddress(data){
        // console.log(data)
        this.formData.form.mapData = data
        this.formData.form.areaCode = data.areaCode
      },
      changeGdArea(data){
        console.log(data)
      },
    },


  };
</script>

<style lang="scss" scoped>
  .e-dialog-footer{
    padding: 20rem 0 4rem 20rem;
    text-align: right;
    box-sizing: border-box;
  }
</style>

